const express = require('express');
const yjstudentControll= require('../controllers/yjstudentControll');
const router =express.Router();
const key="yj11111"

//查询所有/姓名
router.get('/', async (req, res)=>{
    
    const searchName=req.query.searchName;
    console.log("searchName="+searchName)
    var students=null
    if(searchName){
      students=await yjstudentControll.getyname(searchName)
      
    }else{
      console.log('查询所有yo');
      students=await yjstudentControll.getAll()
         
    } 
      if(students){
      console.log("students",students)
      res.status(200).json(students)
    }else{
      console.log("no students")
      res.status(404).json({error:'not found'})
    }
  
})
 //根据id查询书籍
 router.get('/:id', async (req, res) => {
    const yjstudent= await yjstudentControll .getyid(req.params.id);
  if (yjstudent) {
    res.json(yjstudent);
  } else {
    res.status(404).json({ error: 'Student not found' });
  }
});
router.post('/add', async (req, res) => {
  console.log('addRouter'+req.body)
  const result = await yjstudentControll.add(req.body);
// 从结果对象中获取新增数据的ID
const insertId = result.insertId;
// 使用新增数据的ID查询新增的数据
 const newBook = await yjstudentControll.getyid(insertId);
 res.status(201).json(newBook);
});

//根据id修改书籍
router.put('/:id', async (req, res) => {
    const result = await yjstudentControll.update(req.params.id, req.body);
   
    if (result) {
      // 查询更新后的数据
      const newyjstudent = await yjstudentControll.getyid(req.params.id);
  //  const [updatedBook] = await bookquery.query('SELECT * FROM books WHERE id = ?', [id]);
      res.json(newyjstudent);
    } else {
      res.status(404).json({ error: 'Student1 not found' });
    }
});


router.delete('/:id', async (req, res) => {
    const deletedyjstudent = await yjstudentControll.del(req.params.id);
    if (deletedyjstudent) {
      res.json(deletedyjstudent);
    } else {
      res.status(404).json({ error: 'Student2 not found' });
    }
   });
  
   
module.exports = router;

